package reflect;

import jdk.internal.org.objectweb.asm.tree.analysis.Value;
import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;

/*
    调用与当前类Test6在同一个包中被注解@AutoRunClass标注的类中那些被注解接@AutoRunMethod标志的方法若干次（次数由该方法注解的参数确定）
 */
public class Test6 {
    public static void main(String[] args) throws Exception{
        File dir = new File(Test6.class.getResource(".").toURI());
        String packName = Test6.class.getPackage().getName();
        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for (File sub : subs) {
            String fileName = sub.getName();
            String className = fileName.substring(0,fileName.indexOf("."));
            Class cls = Class.forName(packName+"."+className);
            Object obj = cls.newInstance();
            if (cls.isAnnotationPresent(AutoRunClass.class)){
                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AutoRunMethod.class)){
                        System.out.println(method.getName()+"：被注解了");
                        //通过方法对象获取在该方法上 的注解@AutoRunMethod
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        int value = arm.value();//获取该注解的参数
                        System.out.println("开始调用"+ method.getName()+" "+value+"次");
                        for (int i = 0; i < value; i++) {
                            method.invoke(obj);
                        }
                    }
                }
            }
        }
    }
}
